package cn.qianxun.meta.common.security.interceptor;

import cn.qianxun.meta.common.core.annotation.RepeatSubmit;
import cn.qianxun.meta.common.core.exception.ServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author fuzhilin
 * @Date 2023/11/30 10:36
 * @Description
 */
@Component
public class RepeatSubmitInterceptor implements HandlerInterceptor {

        private final Map<String, Long> tokenMap = new ConcurrentHashMap<>();

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                Method method = handlerMethod.getMethod();

                RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);

                if (annotation != null) {
                    long milliseconds = annotation.interval();
                    String tokenKey = buildTokenKey(request);
                    Long lastRequestTime = tokenMap.get(tokenKey);

                    if (lastRequestTime != null && System.currentTimeMillis() - lastRequestTime < milliseconds) {
                       throw new ServiceException(annotation.message());
                    }

                    // 记录本次请求时间
                    tokenMap.put(tokenKey, System.currentTimeMillis());
                }
            }

            return true;
        }

    private String buildTokenKey(HttpServletRequest request) {
        // 在实际应用中，可以根据具体情况构建唯一的key，例如使用用户ID+请求路径
        return request.getRemoteAddr() + ":" + request.getRequestURI();
    }

}